/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.webapp.security;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.jrose.entity.constant.UserType;

import java.io.Serializable;

import static org.jrose.entity.constant.UserType.ANONYMOUS;

public class SecurityCookie implements Serializable {
    private static final long serialVersionUID = 4758977554088249208L;

    static final String COOKIE_NAME = "jrose_security";
    static final String DELIM = "|-|";
    private static final SecurityCookie NIL;

    static {
        NIL = new SecurityCookie();
        NIL.setUsername("");
        NIL.setUserType(ANONYMOUS);
    }

    @Getter @Setter private String username;
    @Getter @Setter private UserType userType;

    public static SecurityCookie load(SecurityCookieManager cookieManager) {
        String value = cookieManager.getCookie(COOKIE_NAME);
        if (value == null) {
            return NIL;
        }
        String[] segments = StringUtils.split(value, DELIM);
        if (segments == null || segments.length != 2) {
            return NIL;
        }
        String username = segments[0];
        UserType userType;
        try {
            userType = UserType.valueOf(segments[1]);
        } catch (IllegalArgumentException ex) {
            userType = ANONYMOUS;
        }
        SecurityCookie cookie = new SecurityCookie();
        cookie.setUsername(username);
        cookie.setUserType(userType);
        return cookie;
    }

    public void save(SecurityCookieManager cookieManager) {
        String value = toCookieValue();
        cookieManager.setSecurityCookie(COOKIE_NAME, value, -1);
    }

    private String toCookieValue() {
        StringBuilder sbuf = new StringBuilder();
        sbuf.append(StringUtils.defaultString(username));
        sbuf.append(DELIM);
        sbuf.append(userType == null ? ANONYMOUS.name() : userType.name());
        return sbuf.toString();
    }
}
